package com.wisdudu.blank.data.source.remote.client.retrofit.client;


import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.wisdudu.blank.app.App;
import com.wisdudu.frame.BuildConfig;
import com.wisdudu.frame.support.util.CacheUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by qyf on 2016/8/17.
 */

public enum OkClient {
    INSTANCE;

    private final OkHttpClient okHttpClient;

    private static final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;

    OkClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        Interceptor cacheInterceptor = new OfflineCacheControlInterceptor();
        short HTTP_CONNECT_TIMEOUT = 10;
        short HTTP_READ_TIMEOUT = 30;
        short HTTP_WRITE_TIMEOUT = 10;
        okHttpClient = new OkHttpClient.Builder()
                //打印日志
                .addInterceptor(interceptor)
                //设置Cache目录
                .cache(new Cache(CacheUtil.getCacheDir(App.getContext()), HTTP_RESPONSE_DISK_CACHE_MAX_SIZE))
                //设置缓存
                .addInterceptor(cacheInterceptor)
                .addNetworkInterceptor(cacheInterceptor)
                .addNetworkInterceptor(new StethoInterceptor())
                //失败重连
                .retryOnConnectionFailure(true)
                //time out
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
                .build()

        ;
    }

    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }
}
